package com.leyou.item.service.impl;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.pojo.Category;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> queryCategoriesByPid(Long id) {
        if(id == null || id.intValue() < 0){
            throw new LyException(ExceptionEnum.PARAMETERS_ILLEGAL_OR_NULL);
        }
        Category category = new Category();
        category.setParentId(id);
        List<Category> categories = this.categoryMapper.select(category);
        if(CollectionUtils.isEmpty(categories)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUNT);
        }
        return categories;
    }

    @Override
    public List<Category> queryByBrandId(Long bid) {
        if(bid == null || bid < 0){
            throw new LyException(ExceptionEnum.PARAMETERS_ILLEGAL_OR_NULL);
        }
        List<Category> list = this.categoryMapper.queryByBrandId(bid);
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUNT);
        }
        return list;
    }

    @Override
    public List<String> queryNamesByIds(List<Long> ids) {
        if(CollectionUtils.isEmpty(ids)){
            throw new LyException(ExceptionEnum.PARAMETERS_ILLEGAL_OR_NULL);
        }
        List<Category> categories = this.categoryMapper.selectByIdList(ids);
        if(CollectionUtils.isEmpty(categories)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUNT);
        }
        return categories.stream().map(Category::getName).collect(Collectors.toList());
    }

    @Override
    public List<Category> queryAllByCid3(Long id) {
        if(id == null || id.intValue() < 0){
            throw new LyException(ExceptionEnum.PARAMETERS_ILLEGAL_OR_NULL);
        }
        Category c3 = this.categoryMapper.selectByPrimaryKey(id);
        Category c2 = null;
        Category c1 = null;
        if(c3 != null){
            c2 = this.categoryMapper.selectByPrimaryKey(c3.getParentId());
        }else {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUNT);
        }
        if(c2 != null){
            c1 = this.categoryMapper.selectByPrimaryKey(c2.getParentId());
        }else {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUNT);
        }
        return Arrays.asList(c1, c2, c3);
    }
}